const Joi = require('joi');

// 用户登录验证
const loginSchema = Joi.object({
  username: Joi.string().min(3).max(50).required(),
  password: Joi.string().min(6).required()
});

// 用户注册验证
const registerSchema = Joi.object({
  username: Joi.string().min(3).max(50).required(),
  password: Joi.string().min(6).required(),
  name: Joi.string().max(100).required(),
  employee_id: Joi.string().max(50),
  department: Joi.string().max(100),
  tenant_id: Joi.number().integer().positive().required(),
  email: Joi.string().email().max(100),
  phone: Joi.string().max(20),
  role: Joi.string().valid('administrator', 'operator', 'user', 'support').default('user')
});

// 工单创建验证
const ticketCreateSchema = Joi.object({
  title: Joi.string().max(200).required(),
  description: Joi.string().required(),
  source_url: Joi.string().max(500).uri(),
  source_type: Joi.string().valid('web', 'mobile', 'api', 'email', 'phone', 'other').default('web'),
  resolution: Joi.string(),
  location: Joi.string().max(200),
  ci_info: Joi.string().max(200),
  product: Joi.string().max(100),
  sub_product: Joi.string().max(100),
  application_id: Joi.number().integer().positive(),
  module_id: Joi.number().integer().positive(),
  product_category_id: Joi.number().integer().positive(),
  incident_level: Joi.string().valid('low', 'medium', 'high', 'urgent').default('medium'),
  impact_scope: Joi.string().valid('individual', 'department', 'company', 'external').default('individual'),
  urgency: Joi.string().valid('low', 'medium', 'high', 'urgent').default('medium'),
  business_impact: Joi.string(),
  workaround: Joi.string(),
  ticket_type: Joi.string().valid('incident', 'request', 'problem', 'change').default('incident'),
  priority: Joi.string().valid('low', 'medium', 'high', 'urgent').default('medium'),
  category: Joi.string().max(100),
  support_staff_id: Joi.number().integer().positive(),
  due_date: Joi.date(),
  estimated_hours: Joi.number().positive().max(999.9),
  tags: Joi.array().items(Joi.string().max(50)).max(10)
});

// 工单更新验证
const ticketUpdateSchema = Joi.object({
  title: Joi.string().max(200),
  description: Joi.string(),
  source_url: Joi.string().max(500).uri(),
  source_type: Joi.string().valid('web', 'mobile', 'api', 'email', 'phone', 'other'),
  resolution: Joi.string(),
  resolution_template_id: Joi.number().integer().positive(),
  location: Joi.string().max(200),
  ci_info: Joi.string().max(200),
  product: Joi.string().max(100),
  sub_product: Joi.string().max(100),
  application_id: Joi.number().integer().positive(),
  module_id: Joi.number().integer().positive(),
  product_category_id: Joi.number().integer().positive(),
  incident_level: Joi.string().valid('low', 'medium', 'high', 'urgent'),
  impact_scope: Joi.string().valid('individual', 'department', 'company', 'external'),
  urgency: Joi.string().valid('low', 'medium', 'high', 'urgent'),
  business_impact: Joi.string(),
  workaround: Joi.string(),
  root_cause: Joi.string(),
  prevention_measures: Joi.string(),
  status: Joi.string().valid('pending', 'in_progress', 'resolved', 'closed', 'cancelled'),
  ticket_type: Joi.string().valid('incident', 'request', 'problem', 'change'),
  priority: Joi.string().valid('low', 'medium', 'high', 'urgent'),
  category: Joi.string().max(100),
  support_staff_id: Joi.number().integer().positive(),
  due_date: Joi.date(),
  estimated_hours: Joi.number().positive().max(999.9),
  actual_hours: Joi.number().positive().max(999.9),
  satisfaction_rating: Joi.number().integer().min(1).max(5),
  satisfaction_feedback: Joi.string(),
  tags: Joi.array().items(Joi.string().max(50)).max(10)
});

// 待办创建验证
const todoCreateSchema = Joi.object({
  title: Joi.string().max(200).required(),
  description: Joi.string(),
  priority: Joi.string().valid('low', 'medium', 'high').default('medium'),
  due_date: Joi.date()
});

// 待办更新验证
const todoUpdateSchema = Joi.object({
  title: Joi.string().max(200),
  description: Joi.string(),
  priority: Joi.string().valid('low', 'medium', 'high'),
  status: Joi.string().valid('pending', 'completed', 'cancelled'),
  due_date: Joi.date()
});

// 用户更新验证
const userUpdateSchema = Joi.object({
  name: Joi.string().max(100),
  employee_id: Joi.string().max(50),
  department: Joi.string().max(100),
  email: Joi.string().email().max(100),
  phone: Joi.string().max(20),
  role: Joi.string().valid('administrator', 'operator', 'user', 'support')
});

// 密码修改验证
const changePasswordSchema = Joi.object({
  oldPassword: Joi.string().required(),
  newPassword: Joi.string().min(6).required()
});

// 部门创建验证
const createDepartmentSchema = Joi.object({
  name: Joi.string().max(100).required(),
  code: Joi.string().max(50).required(),
  parent_id: Joi.number().integer().positive(),
  ancestors: Joi.string().max(500),
  description: Joi.string(),
  contact_phone: Joi.string().max(20),
  location: Joi.string().max(200),
  budget: Joi.number().positive(),
  sort_order: Joi.number().integer().default(0)
});

// 字典类型验证
const lookupTypeSchema = Joi.object({
  code: Joi.string().max(50).required(),
  name: Joi.string().max(100).required(),
  description: Joi.string(),
  sort_order: Joi.number().integer().default(0),
  status: Joi.number().integer().valid(0, 1).default(1)
});

// 字典项验证
const lookupItemSchema = Joi.object({
  type_id: Joi.number().integer().positive().required(),
  parent_id: Joi.number().integer().positive(),
  code: Joi.string().max(50).required(),
  name: Joi.string().max(100).required(),
  value: Joi.string().max(500),
  description: Joi.string(),
  extra_data: Joi.object(),
  sort_order: Joi.number().integer().default(0),
  status: Joi.number().integer().valid(0, 1).default(1)
});

// 验证函数
function validate(schema, data) {
  const { error, value } = schema.validate(data, { abortEarly: false });
  
  if (error) {
    const errors = error.details.map(detail => ({
      field: detail.path.join('.'),
      message: detail.message
    }));
    
    return {
      isValid: false,
      errors,
      data: null
    };
  }
  
  return {
    isValid: true,
    errors: [],
    data: value
  };
}

// 便捷验证方法
function validateLogin(data) {
  return validate(loginSchema, data);
}

function validateRegister(data) {
  return validate(registerSchema, data);
}

function validateTicketCreate(data) {
  return validate(ticketCreateSchema, data);
}

function validateTicketUpdate(data) {
  return validate(ticketUpdateSchema, data);
}

function validateTodoCreate(data) {
  return validate(todoCreateSchema, data);
}

function validateTodoUpdate(data) {
  return validate(todoUpdateSchema, data);
}

function validateUserUpdate(data) {
  return validate(userUpdateSchema, data);
}

function validateChangePassword(data) {
  return validate(changePasswordSchema, data);
}

function validateCreateDepartment(data) {
  return validate(createDepartmentSchema, data);
}

function validateLookupType(data) {
  const result = validate(lookupTypeSchema, data);
  return {
    success: result.isValid,
    data: result.data,
    errors: result.errors,
    message: result.isValid ? '验证通过' : '数据验证失败'
  };
}

function validateLookupItem(data) {
  const result = validate(lookupItemSchema, data);
  return {
    success: result.isValid,
    data: result.data,
    errors: result.errors,
    message: result.isValid ? '验证通过' : '数据验证失败'
  };
}

module.exports = {
  loginSchema,
  registerSchema,
  ticketCreateSchema,
  ticketUpdateSchema,
  todoCreateSchema,
  todoUpdateSchema,
  userUpdateSchema,
  changePasswordSchema,
  createDepartmentSchema,
  lookupTypeSchema,
  lookupItemSchema,
  validate,
  validateLogin,
  validateRegister,
  validateTicketCreate,
  validateTicketUpdate,
  validateTodoCreate,
  validateTodoUpdate,
  validateUserUpdate,
  validateChangePassword,
  validateCreateDepartment,
  validateLookupType,
  validateLookupItem
};